package com.parking.bang.rpc.serialize.kryo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.pool.KryoPool;
import com.parking.bang.rpc.serialize.base.RPCSerialize;

/**
 * Kryo Serialize implement
 * 
 * @author ivan
 *
 */
public class KryoSerialize implements RPCSerialize {

	private KryoPool pool = null;

	public KryoSerialize(KryoPool pool) {
		this.pool = pool;
	}

	public void serialize(OutputStream output, Object object) throws IOException {
		Kryo kryo = pool.borrow();
		Output out = new Output(output);
		kryo.writeClassAndObject(out, object);
		out.close();
		pool.release(kryo);
	}

	public Object deserialize(InputStream input) throws IOException {
		Kryo kryo = pool.borrow();
		Input in = new Input(input);
		Object obj = kryo.readClassAndObject(in);
		in.close();
		pool.release(kryo);
		return obj;
	}

}
